<template>
  <div
    class="m-auto max-w-700 min-w-445 f-c-c rounded-8 bg-#fff bg-cover p-12 card-shadow auto-bg"
  >
    <div class="hidden w-380 px-20 py-35 md:block">
      <img class="w-full" src="../images/ai2.png" alt="login_banner" />
    </div>
    <div class="w-320 flex-col px-20 py-32">
      <div class="text-26 whitespace-nowrap">{{ appStore.info.title }}</div>
      <div class="text-red-600 h-32 lh-32"></div>

      <el-form :model="loginInfo" ref="formEl">
        <el-form-item
          :rules="[{ required: true, message: '' }]"
          name="username"
        >
          <el-input placeholder="请输入用户名" v-model="loginInfo.username">
            <template #prefix>
              <el-icon>
                <User class="text-gray"></User>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          :rules="[{ required: true, message: '' }]"
          name="password"
        >
          <el-input
            type="password"
            placeholder="请输入密码"
            v-model="loginInfo.password"
          >
            <template #prefix>
              <el-icon>
                <Lock class="text-gray"></Lock>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item :rules="[{ required: true, message: '' }]" name="code">
          <el-row :gutter="15">
            <el-col :span="16">
              <el-input
                allow-clear
                placeholder="请输入验证码"
                v-model="loginInfo.code"
              >
                <template #prefix>
                  <el-icon>
                    <Message class="text-gray"></Message>
                  </el-icon>
                </template>
              </el-input>
            </el-col>
            <el-col :span="8">
              <img
                class="cursor-pointer rounded-4"
                @click="getCaptcha()"
                :src="captcha"
                alt=""
              />
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <div class="mb-10">
        <el-checkbox v-model="isRemember">记住密码</el-checkbox>
      </div>

      <el-button
        type="primary"
        size="large"
        class="w-full"
        @click="onLogin"
        :loading="loading"
      >
        登录
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { isEmpty, throttle } from "xe-utils";
import { ref } from "vue";
import userApi, { LoginDto, LoginRes } from "@/api/user.ts";
import { useStorage } from "@vueuse/core";
import { ElMessage } from "element-plus";
import useLoading from "@/hooks/loading.ts";
import { lStorage } from "@/utils/storage";
import { useAuthStore, useAppStore } from "@/store";
import { User, Lock, Message } from "@element-plus/icons-vue";

const formEl = ref();
const isRemember = useStorage("isRemember", true);
const { loading, setLoading } = useLoading();
const authStore = useAuthStore();
const appStore = useAppStore();

const route = useRoute();
const router = useRouter();

const loginInfo = ref<LoginDto>({
  password: null,
  username: null,
  code: null,
});

const captcha = ref("/api/captcha/80/32?t=" + new Date().valueOf());
const getCaptcha = () => {
  throttle(() => {
    captcha.value = "/api/captcha/80/32?t=" + new Date().valueOf();
  }, 500)();
};

const localLoginInfo = lStorage.get("loginInfo");
if (localLoginInfo) {
  loginInfo.value.username = localLoginInfo.username || "";
  loginInfo.value.password = localLoginInfo.password || "";
}

function onLogin() {
  setLoading(true);
  formEl.value
    .validate()
    .then(() => {
      userApi
        .login(loginInfo.value)
        .then((rep) => {
          const { username, password } = loginInfo.value;
          if (isRemember.value) {
            lStorage.set("loginInfo", { username, password });
          } else {
            lStorage.remove("loginInfo");
          }
          onLoginSuccess(rep.data);
          setTimeout(() => {
            setLoading(false);
          }, 1000);
        })
        .catch(() => {
          setLoading(false);
        });
    })
    .catch(() => {
      const { username, password, code } = loginInfo.value;
      if (!username || !password) return ElMessage.error("请输入用户名和密码");
      if (isEmpty(code)) return ElMessage.error("请输入验证码");
      setLoading(false);
    });
}

function onLoginSuccess(res: LoginRes) {
  authStore.setToken(res);

  try {
    ElMessage.success("登录成功");
    if (route.query.redirect) {
      const path = route.query.redirect;
      delete route.query.redirect;

      router.push({ path: path as string, query: route.query });
    } else {
      router.push("/");
    }
  } catch (error) {
    console.error(error);
  }
}
</script>
